<template>
    <el-popover ref="popoverRef" placement="state.placement" width="520" trigger="focus" :hide-after="0" :visible="state.popoverVisible">
        <div class="mp-init" id="mpInit" @mouseover.stop="state.iconSelectorMouseover = true" @mouseout.stop="state.iconSelectorMouseover = false"></div>
        <template #reference>
            <el-input v-model="state.inputValue" placeholder="Please input">
                <template #append>
                    <el-button @click="onInputMarkedMap">
                        <Icon name="el-icon-LocationInformation" />
                    </el-button>
                </template>
            </el-input>
        </template>
    </el-popover>
</template>
<script setup lang="ts">
    import { reactive, ref, onMounted, nextTick, watch, computed, onBeforeUnmount, useTemplateRef  } from 'vue'
    import { useEventListener } from '@vueuse/core'
    import { location } from '/@/api/backend/index'
    import type { Placement } from 'element-plus'
    interface Props {
        modelValue?: string,
        content?:string,
    }
    const props = withDefaults(defineProps<Props>(), {
        modelValue: '',
        content: '',
    })
    const state: {
    popoverMap:any,
    popoverVisible: boolean
    iconSelectorMouseover: boolean,
    inputover: boolean,
    defaultModelValue: string
    placement: Placement
    inputValue: string
    prependIcon: string
} = reactive({
    popoverMap:null,
    popoverVisible: false,
    iconSelectorMouseover:false,
    inputValue: '',
    inputover:false,
    placement: 'bottom',
    defaultModelValue: props.modelValue || '',
    prependIcon: props.modelValue,

})
    const TMap = window.TMap
    let map = null
    let markerLayer = null
    const emits = defineEmits<{
    (e: 'update:modelValue', value: string): void
}>()
    const address2location = async ()=>{
        return  await location({address:'新疆哈密市'+props.content});
    }
    const onInputMarkedMap=()=>{
        state.inputover = !state.inputover;
        state.popoverVisible = state.inputover;
        state.popoverMap = null;
        if(state.popoverVisible){
            
            nextTick(()=>{
                initMap();
            })
            if(props.modelValue == ''){
                address2location().then((res)=>{
                    if(res.code == 1){
                        state.inputValue = res.data.lat.toFixed(6)+','+res.data.lng.toFixed(6);
                        if(props.modelValue == ''){
                            emits('update:modelValue',state.inputValue);
                            addMarker();
                        }
                        
                    }
                })
            }
        }else{
            
        }
    }
    const initMap = ()=> {
        if(map == null){
            let latlng = props.modelValue?props.modelValue.split(','):['42.832672','93.503074'];
            const center = new TMap.LatLng(parseFloat(latlng[0]), parseFloat(latlng[1])); // 设置中心点坐标（例如：北京）
            map = new TMap.Map('mpInit', {
                center: center, // 中心点坐标
                zoom:14,
            })
            console.log(map);
            markerLayer = new TMap.MultiMarker({
                map:map,
            })
            markerLayer.add({
                position: new TMap.LatLng(parseFloat(latlng[0]), parseFloat(latlng[1]))
            })
            map.on('click',clickHandler);
        }
    }

    watch(
        () => props.modelValue,
        () => {
            if (props.modelValue != state.prependIcon) state.defaultModelValue = props.modelValue
            if (props.modelValue == '') state.defaultModelValue = ''
            state.prependIcon = props.modelValue
        }
    )
    const clickHandler =( event )=> {
        const {lat,lng} = event.latLng;
        console.log(lat,lng);
        state.inputValue = lat.toFixed(6)+','+lng.toFixed(6);
        emits('update:modelValue',state.inputValue);
        console.log(state.inputValue);
        console.log(props.modelValue);
        addMarker();

    }
    const addMarker = () => {
        markerLayer.setGeometries([]);
        markerLayer.add({
            position: new TMap.LatLng(parseFloat(state.inputValue.split(',')[0]), parseFloat(state.inputValue.split(',')[1]))
        })
    }
const popoverVisible = () => {
    state.popoverVisible = state.inputover ||  state.iconSelectorMouseover ? true : false
}
    onMounted(() => {
        
        useEventListener(document, 'click', popoverVisible)
        console.log('baLocation mounted')
        
    })
    onBeforeUnmount(() => {
        console.log('baLocation unmounted')
    })
    
</script>
<style scoped lang="scss">
.mp-init{width:500px;height:400px;}
</style>